package com.zzx.boot.utils;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author tan
 * @version 1.0
 * @date 2023/7/7 15:24
 */
@Component
public class RedisUtils {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private final static Gson gson = new Gson();

    /**
     * 获取
     * 设置
     * 设置有时限的
     * 删除
     * 更新
     */

    public <T>T getString(String key,Class<T> clazz){
        return gson.fromJson(stringRedisTemplate.opsForValue().get(key),clazz);
    }

    public <T>T getStringDel(String key,Class<T> clazz){
        return gson.fromJson(stringRedisTemplate.opsForValue().getAndDelete(key),clazz);
    }



    public <T>Boolean setString(String key,T val){
        try {
            stringRedisTemplate.opsForValue().set(key, gson.toJson(val));
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public boolean setStringEx(String key, String val, Long time, TimeUnit timeUnit){
        try {
            stringRedisTemplate.opsForValue().set(key, val,time,timeUnit);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    public boolean delString(String key){
        try {
            stringRedisTemplate.delete(key);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public boolean isStringEx(String key){
        try {
            Long code = stringRedisTemplate.getExpire(key);
            return code != -2;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


}
